import type { Settings as LayoutSettings } from '@ant-design/pro-layout';
import { PageLoading } from '@ant-design/pro-layout';
import type { RunTimeLayoutConfig } from 'umi';
import { history } from 'umi';
import RightContent from '@/components/RightContent';
import Footer from '@/components/Footer';
import { currentUser as queryCurrentUser } from './services/ant-design-pro/api';
import defaultSettings from '../config/defaultSettings';
import { login } from '@/services/ant-design-pro/api';
import React from 'react';

const loginPath = '/user/login';

/** Show a Loading page when loading initial data such as user info slowly */
export const initialStateConfig = {
  loading: <PageLoading />,
};

if (window.location.hostname === 'label.idimage.com.cn') {
  localStorage.setItem('basePath', 'https://label.idimage.com.cn/api');
  localStorage.setItem('Path', `https://label.idimage.com.cn`);
} else {
  const port = window.location.port;
  localStorage.setItem('basePath', `https://${window.location.hostname}:${port}/api`);
  localStorage.setItem('Path', `https://${window.location.hostname}`);
}
console.log('wind', window.location.hostname);

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  loading?: boolean;
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
}> {
  const fetchUserInfo = async () => {
    try {
      const msg = await queryCurrentUser();
      return msg.data;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };

  const handleSubmit = async (code: string) => {
    try {
      const msg = await login(code);
      console.log('login', msg);
      if (msg.status === 200) {
        localStorage.setItem('Access_Token', msg.result.token);
        localStorage.setItem('Role', msg.result.role);
        localStorage.setItem('username', msg.result.username);
        await fetchUserInfo();
        // Redirect to the original path or home
        const { query } = history.location;
        const { redirect } = query as { redirect: string };
        history.push(redirect || '/');
        return;
      }
      console.error(msg);
      throw new Error('登录失败，请重试');
    } catch (error) {
      console.error('登录失败:', error);
      // 清除登录状态
      localStorage.removeItem('Access_Token');
      localStorage.removeItem('Role');
      localStorage.removeItem('username');
      goToLogin();
    }
  };

  const goToLogin = async () => {
    console.log("goToLogin");
    const url = 'https://ucenterd.icaiji.com.cn/?';
    const app = 112;
    const subject = 112;
    const redirect = localStorage.getItem('Path'); // Path is for production  basePath is for local
    console.log("redirect", redirect);
    // Use window.open for redirection
    window.open(
      url + 'r=' + window.btoa(`redirect=${redirect}&app=${app}&subject=${subject}`),
      '_self'
    );
  };

  const token = localStorage.getItem('Access_Token');
  const urlParams = new URLSearchParams(window.location.search);
  const code = urlParams.get('code');

  if (!token || token == null) {
    if (!code) {
      goToLogin();
    }
  }

  const Access_Token = urlParams.get('code');
  if (Access_Token) {
    await handleSubmit(Access_Token);
  }

  return {
    fetchUserInfo,
    acc_token: localStorage.getItem('Access_Token'),
    goToLogin,
    settings: defaultSettings,
  };
}

// ProLayout supports these APIs: https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  return {
    rightContentRender: () => (
      <>
        <RightContent />
        <button
          style={{
            backgroundColor: '#1824c4',
            color: 'white',
            border: 'none',
            padding: 0,
            cursor: 'pointer',
            fontSize: '16px',
            borderRadius: '5px',
            transition: 'background-color 0.3s ease',
          }}
          onClick={() => {
            localStorage.removeItem('Access_Token');
            localStorage.removeItem('Role');
            localStorage.removeItem('username');
            initialState?.goToLogin();
          }}
        >
          退出
        </button>
      </>
    ),
    disableContentMargin: false,
    waterMarkProps: {
      content: initialState?.acc_token,
    },
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      const acc_token = localStorage.getItem('Access_Token');
      if (!acc_token) {
        initialState?.goToLogin();
      }
    },
    links: [],
    title: '',
    menuHeaderRender: undefined,
    childrenRender: (children) => {
      if (initialState?.loading) return <PageLoading />;
      return <>{children}</>;
    },
    ...initialState?.settings,
  };
};